package com.rhythms.swiperecyclerview;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

import com.rhythms.swiperecyclerview.bean.RhythmsItemBean;
import com.rhythms.swiperecyclerview.listener.OnItemPlayListener;
import com.rhythms.swiperecyclerview.utils.RhythmsStaticConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RhythmsPlaySound {

    private static RhythmsPlaySound instance = new RhythmsPlaySound();
    private RhythmsPlaySound (){}
    public static RhythmsPlaySound getInstance() {
        return instance;
    }
    SoundPool sp;
    HashMap<Integer, Integer> sounddata;
    float volumnCurrent;
    float volumnRatio;
    Boolean isLoaded;
    /**
     * 相关变量初始化
     */
    public void init(Context context) {
//        timer = new Timer();
//        timeIntent = new Intent();

        sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        sounddata = new HashMap<Integer, Integer>();
        for (int i = 0; i < RhythmsStaticConstants.SOUND_RAW_IDS.length; i++) {
            sounddata.put(i, sp.load(context, RhythmsStaticConstants.SOUND_RAW_IDS[i], 1));
        }
        sp.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool sound, int sampleId, int status) {
                isLoaded = true;
//				Toast.makeText(mcontext,
//						"音效加载完成！",
//						Toast.LENGTH_SHORT);
            }
        });

        AudioManager am = (AudioManager) context
                .getSystemService(Context.AUDIO_SERVICE);
        float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        volumnRatio = volumnCurrent / audioMaxVolumn;
    }


    public void playSound(int sound, int number) {

        sp.play(sounddata.get(sound),
                volumnRatio,// 左声道音量
                volumnRatio,// 右声道音量
                1, // 优先级
                number,// 循环播放次数
                1);// 回放速度，该值在0.5-2.0之间 1为正常速度
    }


    public void startOneCycles(final int position, final List<RhythmsItemBean> mRhythmsItemBeanList, final OnItemPlayListener playListener) {
        final List<RhythmsItemBean> selectRhythmsItemBeanList = new ArrayList<>();
        for (int i = 0; i < mRhythmsItemBeanList.size(); i++) {
            RhythmsItemBean rhythmsItemBean = mRhythmsItemBeanList.get(i);
            if(rhythmsItemBean.isRhySelect()){
                selectRhythmsItemBeanList.add(rhythmsItemBean);
            }
        }
        // 如果位置超过数组则循环完毕
        if (position >= selectRhythmsItemBeanList.size() || position < 0) {
            return;
        }
        Log.i("ddkkkdddkk", "position:== "+position);
        playListener.onItemPlay(position);
        final RhythmsItemBean rhythmsItemBean = selectRhythmsItemBeanList.get(position);
        Log.i("ddkkkdddkk", "size:== "+selectRhythmsItemBeanList.size());
        stopOneCycles();
        long rhyData = rhythmsItemBean.getRhyPeriod().getRhyData();
        long rhyPeriod = 60000/rhyData;
        Log.i("ddkkkdddkk", "getRhyPeriod:== "+rhyData);
        Log.i("ddkkkdddkk", "getRhyPeriod--:== "+rhyPeriod);
        Observable.interval(0, rhyPeriod, TimeUnit.MILLISECONDS)
                .take(rhythmsItemBean.getRhyCycles().getRhyData() * rhythmsItemBean.getRhyTimes().getRhyData())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
//                        hsballIdVerifyCodeResend.setEnabled(false);
//                        hsballIdVerifyCodeResend.setTextColor(getResources().getColor(R.color.hsball_color_grey));
                    }
                })
                .doFinally(new Action() {
                    @Override
                    public void run() throws Exception {
//                        hsballIdVerifyCodeResend.setEnabled(true);
//                        hsballIdVerifyCodeResend.setTextColor(getResources().getColor(R.color.hsball_color_main_bluish));
                    }
                })
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
//                        Log.i("ddkkkdddkk", "onSubscribe:== "+rhythmsItemBean.getStartSoundID());
//                        playSound(rhythmsItemBean.getStartSoundID(), 0);
                    }

                    @Override
                    public void onNext(Long aLong) {
//                        hsballIdVerifyCodeResendTime.setText("("+aLong+")");
                        Log.i("ddkkkdddkk", "aLong:== "+aLong);
//                        Log.i("ddkkkdddkk", "onNext:== "+rhythmsItemBean.getSoundID());
                        if (aLong % rhythmsItemBean.getRhyTimes().getRhyData() == 0) {
                            playSound((int)rhythmsItemBean.getRhyStartSound().getRhyData(), 0);
                        } else {
                            playSound((int)rhythmsItemBean.getRhyRateSound().getRhyData(), 0);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
//                        hsballIdVerifyCodeResend.setEnabled(true);
//                        hsballIdVerifyCodeResend.setTextColor(getResources().getColor(R.color.hsball_color_main_bluish));
//                        hsballIdVerifyCodeResendTime.setText("");
                        Log.i("ddkkkdddkk", "onComplete-====================--size:== "+selectRhythmsItemBeanList.size());
                        if (selectRhythmsItemBeanList.size() > 1) {
                            startOneCycles(position + 1, mRhythmsItemBeanList, playListener);
                        }
                    }
                });
    }

    private Disposable mDisposable;

    /**
     * 关闭定时器
     */
    public void stopOneCycles() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
    }
}
